package cn.edu.scnu.Service.impl;

import cn.edu.scnu.Mapper.BookMapper;
import cn.edu.scnu.Service.BookService;
import cn.edu.scnu.entity.Book;
import cn.edu.scnu.entity.Return;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService{
    @Autowired
    public BookMapper bookMapper;
    @Override
    public Return findAll() {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        List<Book> books = bookMapper.selectList(lqw);
        return new Return().sussess(books);
    }

    @Override
    public Return getPage(int currentPage, int size, String category, String bookName) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        if(!category.equals("全部图书")){
            lqw.eq(Book::getType, category);
        }else{//进行搜索时，需把图书种类置为“全部图书”
            lqw.like(Book::getBookName, bookName);
        }
        IPage<Book> iPage = new Page<>(currentPage, size);
        bookMapper.selectPage(iPage, lqw);
        return new Return().sussess(iPage);
    }

    @Override
    public Return getCategory() {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.select(Book::getType);
        lqw.groupBy(Book::getType);
        List<Object> list = bookMapper.selectObjs(lqw);
        return new Return().sussess(list);
    }

    @Override
    public Return getByCategory(String category) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Book::getType, category);
        List<Book> books = bookMapper.selectList(lqw);
        return new Return().sussess(books);
    }

    @Override
    public Return getBookById(String bookId) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Book::getBookId, bookId);
        Book book = bookMapper.selectOne(lqw);
        return new Return().sussess(book);
    }

    @Override
    public Return getBookByBookName(int currentPage, int size, String bookName) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(Book::getBookName, bookName);
        IPage<Book> iPage = new Page<>(currentPage, size);
        bookMapper.selectPage(iPage, lqw);
        if(iPage.getTotal() == 0){//没有数据
            return new Return().error("该图书未上架!_!");
        }
        return new Return().sussess(iPage);
    }


}
